var express=require('express');
var path = require('path')
var app=express();
app.use(express.static(path.join(__dirname,'./')))
var http=require('http').Server(app);
var io=require('socket.io')(http);

http.listen(3000,function(){
    console.log('server begin...');
});
var connectionList = {};
io.on('connection',function(socket){
    //客户端连接时，保存socketId和用户名
    connectionList[socket.id] = {
        socket:socket,
        name:'新人'+ new Date().getTime()
    }
    socket.emit('newperson', getSendMsg(socket.id, ''));
    //监听客户端的chat message事件， 该事件由客户端触发
    //当服务端收到消息后，再把该消息播放出去，继续触发chat message事件， 然后在客户端监听chat message事件。
    socket.on('setname',function(msg){
        connectionList[socket.id].name = msg
        //判断是不是第一次连接，以第一条消息作为昵称
        sendM(socket,socket.id,connectionList[socket.id].name +':改名叫----'+ msg)
    });
    socket.on('setmsg',function(msg){
        sendM(socket,socket.id,connectionList[socket.id].name +':'+msg)
    });
    socket.on('disconnect',function(){
        var msg = connectionList[socket.id].name + ':退登了'
        delete connectionList[socket.id]
        sendM(socket,socket.id,msg,true)
    });
});
function getSendMsg (id, m) {
    return {
        peoples: Object.keys(connectionList).map(function (o) {
            return {
                socket:connectionList[o].socket.id,
                name: connectionList[o].name
            }
        }),
        info: {
            uid: id,
            msg: m
        }
    }
}
function sendM(e,id, m, b) {
    e.emit('system',  getSendMsg(id,m))
    !b&&e.broadcast.emit('system',  getSendMsg(id,m))
}
